package com.modul.simpleLock.testlock;

import com.modul.simpleLock.lockservice.RedisLock;
import com.modul.simpleLock.lockservice.ReentrantRedisLock;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * @Author: sijunqiang
 * @Date: 2020/6/6 19:28
 * @Description: 测试可重入锁的代码
 */

@Slf4j
@Component
@AllArgsConstructor(onConstructor = @__(@Autowired))
public class TestReentrantJob {

    private final StringRedisTemplate redisTemplate;

    private Integer max = 2;


    @Scheduled(cron = "0/10 * * * * ?")
    public void TestReentrantLock() {

        // c创建锁对象
        RedisLock lock = new ReentrantRedisLock(redisTemplate, "luaLock");
        // 开始执行锁任务
        runTaskWithLock(lock, 1);
    }


    public void runTaskWithLock(RedisLock lock, int count) {
        //  获取锁 设置自动失效的时间
        Boolean aBoolean = lock.tryLock(50);
        if (!aBoolean) {
            // false 获取失败 true 获取成功
            log.info("第[{}]层，获取锁失败，停止定时任务", count);
        }

        try {
            log.info("第[{}]层，获取锁成功，开始执行当前拥有锁的逻辑......", count);
            Thread.sleep(2000);
            if (count < max) runTaskWithLock(lock, count + 1);
        } catch (InterruptedException e) {
            log.error("第[{}]层，任务执行失败", count);
        }finally {
            lock.unlock();
            log.info("第[{}]层，任务执行完毕，释放锁", count);
        }


    }


}
